package org.layui.servlet;


import org.layui.dao.UserDao;
import org.layui.dao.impl.UserDaoImpl;
import org.layui.entity.User;
import org.layui.utils.JwtUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/api/user/changePwd")
public class UserChangePassServlet extends BaseServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String password = req.getParameter("password");
        String newPass = req.getParameter("newPass");
        String confirmPass = req.getParameter("confirmPass");

        if(newPass==null || !newPass.equals(confirmPass)) {
            print(resp, successJson(null,500,"两次密码不一致"));
        }

        // 获取客户端发送过来的token
        String jwt = getJwt(req);

        // 获取payload信息
        String username = JwtUtil.getPayload(jwt, "username", String.class);
        UserDao userDao = new UserDaoImpl();
        User user = userDao.selectUser(username);

        if(user!=null && !user.getPassword().trim().equals(password)) {
            print(resp, successJson(null,500,"密码不正确"));
        }

        userDao.updatePwd(username,newPass);

        print(resp, successJson(null,200,"修改密码成功"));
    }
}
